﻿using System;
using System.Collections.Generic;
using Rabbit.Logic;
using RabbitShop.Code;

namespace RabbitShop.Action
{
    public partial class OrderAdd : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string uid = string.Empty;
            if (Request.Cookies[Constant.CookieName] != null)
            {
                uid = Request.Cookies[Constant.CookieName].Values[Constant.CookieUid];
                if (string.IsNullOrEmpty(uid)) Response.Redirect("~/UI/UserLogon.aspx");
            }
            else
            {
                Response.Redirect("~/UI/UserLogon.aspx");
            }

            Customer customer = RabbitUse.GetCustomerById(Db.Store, uid);
            if (customer.PreOrderShopItem == null || customer.AddressList == null)
            {
                Response.Write("false");
                return;
            }
            if (customer.AddressList.Count < customer.DefaultAddressIndex + 1)
            {
                Response.Write("false");
                return;
            }

            Order order = new Order();
            order.CustomerId = customer.Id;
            order.ShipTo = customer.AddressList[customer.DefaultAddressIndex];
            order.ShopId = customer.PreOrderShopItem.ShopId;

            List<ProductSnapWithQuantity> snaps = new List<ProductSnapWithQuantity>();
            order.Items = RabbitPunch.PrepareProduct(customer, snaps);
            order.Total = NoDb.ComputeCartTotal(snaps);

            ShipRule rule = RabbitUse.GetShipRuleByShopId(Db.Store, customer.PreOrderShopItem.ShopId);

            Shop shop = RabbitUse.GetShopByShopId(Db.Store, customer.PreOrderShopItem.ShopId);
            DiliveryPriceResult diliveryPrice = NoDb.ComputeDiliveryCost(shop.FreeShipAt, order.Total, rule, order.ShipTo, shop.Location, customer.IsNear);

            order.DiliveryPrice = diliveryPrice.Price;
            order.FinalPrice = order.Total.TotalPrice + diliveryPrice.Price;
            order.OrderedAt = DateTime.Now;

            CustomerOrderMapping customerOrderMapping = RabbitPunch.PrepareCustomerOrderMapping(customer);
            RabbitPunch.CorrectShopOrderMapping(shop);
            ShopOrderMapping shopOrderMapping = RabbitPunch.PrepareShopOrderMapping(shop);

            RabbitPunch.AddOrder(Db.Store, order, customerOrderMapping, shopOrderMapping);
            
            RabbitPunch.RemoveBought(Db.Store, customer);
            
            Logic.UpdateCookieCartNo(this, customer.ShopList.Count.ToString());

            Response.Write("true");
        }
    }
}